import { fileURLToPath, URL } from 'node:url'
import path from 'path'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import FileName from '@ebag/rollup-plugin-file-naming'
import pxtorem from 'postcss-pxtorem'
import svgLoader from 'vite-svg-loader'

import Icons from 'unplugin-icons/vite'
import IconsResolver from 'unplugin-icons/resolver'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import {
  AntDesignVueResolver,
  ElementPlusResolver
} from 'unplugin-vue-components/resolvers'

function getBaseURL() {
  let baseURL = ''
  const deployEnv = process.env.DREAMENV
  const date = new Date()
  let prefix = `${process.env.CI_PROJECT_NAME}/${date.getFullYear()}${
    date.getMonth() + 1
  }${date.getDate()}`
  switch (deployEnv) {
    case 'TEST':
      baseURL = process.env.TEST_RESOURCE_DOMAIN + prefix
      break
    case 'PROD':
      baseURL = process.env.PROD_RESOURCE_DOMAIN + prefix
      break
    default:
      baseURL = './'
      break
  }
  return baseURL
}

const pathSrc = path.resolve(__dirname, 'src')
// https://vitejs.dev/config/
export default defineConfig({
  base: getBaseURL(),
  build: {
    target: 'chrome74'
  },
  plugins: [
    vue({
      template: {
        compilerOptions: {
          isCustomElement: tag => ['micro-app'].includes(tag)
        }
      }
    }),
    FileName(),
    svgLoader(),
    AutoImport({
      imports: ['vue'],
      resolvers: [
        ElementPlusResolver(),
        AntDesignVueResolver(),
        IconsResolver({
          prefix: 'Icon'
        })
      ],
      dts: path.resolve(pathSrc, 'auto-imports.d.ts')
    }),
    Components({
      resolvers: [
        IconsResolver({
          enabledCollections: ['ep']
        }),
        ElementPlusResolver(),
        AntDesignVueResolver()
      ],
      dts: path.resolve(pathSrc, 'components.d.ts')
    }),
    Icons({
      autoInstall: true
    })
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  css: {
    preprocessorOptions: {
      less: {
        charset: false,
        additionalData: `@import "${path.resolve(
          __dirname,
          'src/assets/css/constant.less'
        )}";@import "${path.resolve(__dirname, 'src/assets/css/readboy.less')}";`,
        javascriptEnabled: true
      }
    },
    postcss: {
      plugins: [
        pxtorem({
          rootValue: 192, // 这里写设计稿的宽度/10即可，例如设计稿宽度是1920px就写192
          propList: ['*'], // 需要转换的属性，默认转换所有属性
          selectorBlackList: [], // CSS选择器黑名单，防止部分选择器被转换
          include: /node_modules\/(element-plus|ant-design-vue)\//,
          exclude: /node_modules\/(?!(element-plus|ant-design-vue))/
        })
      ]
    }
  }
})
